package com.gq.rising.util;

import com.gq.rising.common.DbSource;
import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.util.Map;

/**
 * 数据库工具类
 */
public class DbUtils {

    /**
     * 根据输入参数构建数据源model
     */
    public DbSource buildDataSource(DbSource dbSource, Map<String, Object> inputBoxValue) throws RuntimeException{
        if("MySql".equals(dbSource.getName())){
            dbSource.setUrl("jdbc:mysql://"+inputBoxValue.get("boxHost").toString()+":"+inputBoxValue.get("port").toString()+"/yun6?serverTimezone=GMT&useUnicode=true&characterEncoding=UTF8");
        }else{
            dbSource.setUrl(inputBoxValue.get("boxHost").toString());
        }
        dbSource.setPort(inputBoxValue.get("port").toString());
        dbSource.setUsername(inputBoxValue.get("userName").toString());
        dbSource.setPassword(inputBoxValue.get("pwWord").toString());

        return dbSource;
    }

    /**
     * 根据数据源model获取连接对象
     */
    public Connection getConnection(DbSource dataSource) throws Exception{
        return this.getDataSource(dataSource).getConnection();
    }

    /**
     * 根据数据源model获取HikariDataSource数据源
     */
    public HikariDataSource getHikariDataSource(DbSource dbSource) throws Exception{
        return this.getDataSource(dbSource);
    }

    /**
     * 得到springboot的默认数据源Hikari
     * @return HikariDataSource
     */
    public HikariDataSource getDataSource(DbSource dbSource){
        // 创建一个数据源对象
        HikariDataSource hikariDataSource = new HikariDataSource();
        // 数据库地址 jdbc:oracle:thin:@172.16.5.254:1521:ORCL
        hikariDataSource.setJdbcUrl(dbSource.getUrl());
        // 驱动oracle.jdbc.driver.OracleDriver
        hikariDataSource.setDriverClassName(dbSource.getDriverClassName());
        // 用户名
        hikariDataSource.setUsername(dbSource.getUsername());
        // 密码
        hikariDataSource.setPassword(dbSource.getPassword());
        return hikariDataSource;
    }
}
